package com.ctakit.sdk.app.util;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Parcelable;
import android.view.TouchDelegate;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.ctakit.sdk.Sdk;
import com.ctakit.sdk.app.R;
import com.ctakit.sdk.app.base.MyActivity;

import java.io.Serializable;
import java.util.Map;

/**
 * Created by imuto on 16/05/20.
 */
public class ViewUtil {

    /**
     * 增大view的点击区域(单位dp)
     *
     * @param view
     * @param lAdd
     * @param tAdd
     * @param rAdd
     * @param bAdd
     */
    public static void increaseClickRegion(final View view, final int lAdd, final int tAdd, final int rAdd, final int bAdd) {
        if (view == null) return;
        final View parent = (View) view.getParent();
        if (parent == null) return;
        parent.post(new Runnable() {
            @Override
            public void run() {
                Rect bounds = new Rect();
                view.getHitRect(bounds);
                bounds.left -= DensityUtil.dip2px(lAdd);
                bounds.top -= DensityUtil.dip2px(tAdd);
                bounds.right += DensityUtil.dip2px(rAdd);
                bounds.bottom += DensityUtil.dip2px(bAdd);
                TouchDelegate touchDelegate = new TouchDelegate(bounds, view);

                parent.setTouchDelegate(touchDelegate);
            }
        });
    }

    /**
     * 屏幕宽度
     */
    public static int getScreenWidth() {
        return Sdk.app().getResources().getDisplayMetrics().widthPixels;
    }

    /**
     * 屏幕高度
     */
    public static int getScreenHeight() {
        return Sdk.app().getResources().getDisplayMetrics().heightPixels;
    }

    /**
     * 获取控件宽
     */
    public static int getWidth(View view) {
        int width = view.getWidth();
        if (width > 0) {
            return width;
        }

        ViewGroup.LayoutParams params = view.getLayoutParams();
        int w = params != null ? params.width : 0;
        if (w > 0) {
            return w;
        }
        w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        view.measure(w, h);
        return (view.getMeasuredWidth());
    }

    /**
     * 获取控件高
     */
    public static int getHeight(View view) {
        int height = view.getHeight();
        if (height > 0) {
            return height;
        }
        ViewGroup.LayoutParams params = view.getLayoutParams();
        int h = params != null ? params.height : 0;
        if (h > 0) {
            return h;
        }
        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        view.measure(w, h);
        return (view.getMeasuredHeight());
    }

    /**
     * 获取文字高度
     */
    public static int getFontHeight(float fontSize) {
        Paint paint = new Paint();
        paint.setTextSize(fontSize);
        Paint.FontMetrics fm = paint.getFontMetrics();
        return (int) Math.ceil(fm.descent - fm.ascent);
    }

    public static void setBackground(View view, Drawable drawable) {
        if (Build.VERSION.SDK_INT < 16) {
            view.setBackgroundDrawable(drawable);
        } else {
            view.setBackground(drawable);
        }
    }
    public static void setImageDrawable(ImageView view, Drawable drawable) {
        view.setImageDrawable(drawable);
    }


    // 跳转到下一个 activity

    public static void gotoActivity(final MyActivity myActivity, Class<?> clazz, Map<String, Serializable> data,Map<String, Parcelable> parcelableMap) {

        startMyActivity(myActivity, clazz, data,parcelableMap, -1);

    }


    private static void startMyActivity(final MyActivity myActivity, Class<?> clazz, Map<String, Serializable> data,Map<String, Parcelable> parcelableMap, int flags) {

        Intent intent = new Intent();
        if (flags != -1) {
            intent.setFlags(flags);
        }
        intent.setClass(myActivity.getActivity(), clazz);

        if (data != null && !data.isEmpty()) {
            for (Map.Entry<String, Serializable> entry : data.entrySet()) {
                intent.putExtra(entry.getKey(), entry.getValue());

            }
        }

        if (parcelableMap != null && !parcelableMap.isEmpty()) {
            for (Map.Entry<String, Parcelable> entry : parcelableMap.entrySet()) {
                intent.putExtra(entry.getKey(), entry.getValue());
            }
        }

        myActivity.getActivity().startActivity(intent);
        enterAnim(myActivity.getActivity());

    }

    public static void gotoActivityWithClearTop(final MyActivity myactivity, Class<?> clazz, Map<String, Serializable> data,Map<String, Parcelable> parcelableMap) {

        startMyActivity(myactivity, clazz, data,parcelableMap, Intent.FLAG_ACTIVITY_CLEAR_TOP);

    }

    // 跳转到下一个 activity
    public static void gotoActivityForResult(final Activity activity, Class<?> clazz, Map<String, Serializable> data) {
        Intent intent = new Intent();
        intent.setClass(activity, clazz);

        if (data != null && !data.isEmpty()) {
            for (Map.Entry<String, Serializable> entry : data.entrySet()) {
                intent.putExtra(entry.getKey(), entry.getValue());

            }
        }
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        activity.startActivityForResult(intent, 0);
    }

    public static void bottomToActivity(final Activity activity, Class<?> clazz, Map<String, Serializable> data) {

        Intent intent = new Intent();
        intent.setClass(activity, clazz);
        if (data != null && !data.isEmpty()) {
            for (Map.Entry<String, Serializable> entry : data.entrySet()) {
                intent.putExtra(entry.getKey(), entry.getValue());

            }
        }
        bottomEnterAnim(activity);
        activity.startActivity(intent);


    }

    // 跳转到下一个 activity(不传数据)
    public static void gotoActivity(final MyActivity myActivity, Class<?> clazz) {
        gotoActivity(myActivity, clazz, null,null);
    }


    // 设置切换动画，从右边进入，左边退出
    public static void enterAnim(final Activity activity) {
        activity.overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
    }

    // 设置切换动画，从下向上边进入，左边退出
    public static void bottomEnterAnim(final Activity activity) {
        activity.overridePendingTransition(R.anim.menu_bottom_open_in, R.anim.still);
    }

    // 设置切换动画，从右边进入，左边退出
    public static void exitAnim(final Activity activity) {
        activity.overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
    }

    // 设置切换动画，从上向下边退出
    public static void bottomExitAnim(final Activity activity) {
        activity.overridePendingTransition(R.anim.still, R.anim.menu_bottom_close_in);
    }

    //设置文本内容
    public static void setTextView(MyActivity myActivity, String text, int id) {
       View v = myActivity.findView(id);

        if(v!=null&&v instanceof TextView&&text!=null){
            ((TextView)v).setText(text);
        }
    } //设置文本内容
    public static void setTextView(View view, String text, int id) {
       View v = view.findViewById(id);

        if(v!=null&&v instanceof TextView&&text!=null){
            ((TextView)v).setText(text);
        }
    }

    public static void onTextChangedFormate(EditText view, char split, int[] splitPosition, CharSequence s, int start, int before, int after) {
        if (s == null || s.length() == 0) {
            return;
        }

        int indexLength = 0;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            if (i < start && s.charAt(i) == split) {
                indexLength--;
            }
            if (s.charAt(i) != split) {
                sb.append(s.charAt(i));
            }

            if (MyNumberUtils.isInArray(sb.length(), splitPosition) && sb.charAt(sb.length() - 1) != split) {
                if (sb.length() <= start + after) {
                    indexLength++;

                }
                sb.insert(sb.length() - 1, split);
            }

        }
        if (!sb.toString().equals(s.toString())) {


            int index = start + indexLength + after;
            if (MyNumberUtils.isInArray(index, splitPosition)) {
                index--;
            }
            if (index < 0) {
                index = 0;
            }
            int len = sb.length();
            view.setText(sb.toString());
            len = len < view.length() ? len : view.length();

            view.setSelection(index > len ? len : index);
//            view.setText(sb.toString());
//            view.setSelection(index > sb.length() ? sb.length() : index);

        }
    }
}
